<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

class ImgUploadController extends Controller
{
    //
    public function categoriesImg(Request $request){

        if($request->isMethod('POST')){

            $file = $request->file('categories_img');
            $name = $request->input('name');
            $categories_id = $request->input('categories_id');
            if($file->isValid()){

                $mimetype = $file->getClientMimeType();
                $originalName = $file->getClientOriginalName();

                $ext = $file->getClientOriginalExtension();
                $realPath = $file->getRealPath();

                $filename = $name.'.jpg';

                $bool = Storage::disk('upload')->put($filename,file_get_contents($realPath));

                $path = "/../public/uploads/";

                $result = DB::table('categories')->where('categories_id',$categories_id)->update([
                    'categories_img'=> $filename,
                ]);
                    return Redirect('updateCategories.html?id='.$categories_id );
//                header("Content-type:image/jpg");
//                readfile($_SERVER['DOCUMENT_ROOT'].'/uploads/'.$filename);
            }
            exit;
        }

    }

    public  function getImage(Request $request)
    {
        $image_id = $request->input('id');
        if($image_id == 0)
        {
            header("Content-type:image/jpg");
            readfile($_SERVER["DOCUMENT_ROOT"]."/uploads/default.jpg");
        }
        $imageData = DB::table("categories")
            ->where("categories_id","=",$image_id)
            ->first();
        if($imageData!=NULL)
        {header("Content-type:image/jpg");
            readfile($_SERVER['DOCUMENT_ROOT'].'/uploads/'.$imageData->categories_img);
        }
        else //如果没有图片的，换上一张默认图片
        {
            header("Content-type:image/jpg");
            readfile($_SERVER["DOCUMENT_ROOT"]."/uploads/default.jpg");
        }
    }
}
